//根据id返回元素的引用,是document.getElementById的别名
function $O(id){ return document.getElementById(id);}
//根据name返回元素的引用数组,是document.getElementsByName的别名
function $N(name){ return document.getElementsByName(name);}
//String的两个函数，实现去空格，和左边去0
String.prototype.trim=function(){  return this.replace(/(^\s+)|(\s+$)/g,""); }
String.prototype.lzero=function(){ return this.replace(/\b(0+)/gi,"")};

//按名字取得cookie内容
function getCookie(name){
	var cookie = document.cookie;
	var i = cookie.indexOf(" "+name+"=");
	if(cookie.substring(0,name.length)==name )	i=0;
	if(i<0)	return "";
	var j = cookie.indexOf(";", i),	k = cookie.indexOf("=", i);
	return cookie.substring(k+1, j>0?j:cookie.length);
	//var m = document.cookie.match(new RegExp("(^|;|\\b)*"+name+"=([^;]*)(;|$)"));
	//return (!m?"":m[2]);
}
//设置指定名字的cookie内容
function setCookie(name,value,path,domain,expires){
    if(!path) var path="/";
    if(!domain) var domain="stone.com";
	
    document.cookie = name + "=" + value + "; path="+path+"; domain="+domain + (expires ? "; expires="+expires:"");
}
//删除cookie内容
function deleteCookie(name){
    if(!path) var path="/";
    if(!domain) var domain="stone.com";
    document.cookie = name + "=" + "; path=" + path + "; domain=" + domain + "; expires=Thu, 1 Jan 1970 00:00:01 UTC";
}

//给定的字符串转为json类型 param string to json
function getArgs(query) {
    query = query==null?"":query;
    var args = {},pairs = query.split("&");
    for(var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('=')
        if ( pos == -1) continue;
        args[pairs[i].substring(0,pos)] = decodeURIComponent(pairs[i].substring(pos+1));
    }
    return args;
}
//把URL带的参数(location.search)转为json类型 param string to json
function getHrefArgs() { return getArgs(location.search.substring(1)); }

/**
 * 判断是否为中文
 * @param {String} s,  要判断的字符串
 * @return 若是中文返回true，否则返回false
 */
function chkChinese(s){
	for(var i = 0; i < s.length; i++){
		if(s.charCodeAt(i)>255)
		  return true;
	}
	return false;
};

/**
 * 定义验证各种格式类型的正则表达式对象
 */
var Regexs = {
  email:   (/^[0-9a-z][0-9a-z\-\_\.]+@([0-9a-z][0-9a-z\-]*\.)+[a-z]{2,}$/i),
  phone:   (/^(\d+-)*\d{6,}$/),
  url:     (/^http:\/\/([0-9a-z][0-9a-z\-]*\.)+[a-z]{2,}(:\d+)?\/[0-9a-z%\-_\/\.]+/i),
  num:    (/[^0-9]/g),
  cnum:	  (/[^0-9a-zA-Z]/g),
  photo:   (/\.jpg$|\.jpeg$|\.gif$/i),
  row:     (/\n/ig) 
};

/**
 * 验证页面对象中的value是否符合指定的格式
 * @scope private
 * @static
 * @param {String} value, 要验证内容
 * @param {String} ftype ,要验证的格式类别
 * @return 若符合对应的格式，返回true，否则返回false
 */
function chkFormat(str,ftype){	
	var nReg  = Regexs[ftype];	
	if(str == null||str == "") return false;	//输入为空，认为是验证通过
	if(ftype == 'num'){
		if(!nReg.test(str)&&!chkChinese(str)){//10.23 tenfy 必须为数字且不能有中文
			 return true;
		} else{
			return false;
		}
	}
	if(!nReg.test(str)){
		return true;
	} else{
		return false;
	}
};


function isGmcc(pn){
	var regyd = /^1(3[4-9]\d{8}|5[021789]\d{8}|8[78]\d{8})$/;
	return regyd.test(pn);
}
/*
 * 验证给定字符串是否联通手机号码
*/
function isUnicom(pn){
	var reglt = /^1(3[0-2]\d{8}|5[356]\d{8}|8[56]\d{8})$/;
	return reglt.test(pn);
}
/*
 * 验证给定字符串是否手机号码
*/
function isPhone(pn){
	var regs = /^1[358]\d{9}$/;
	return regs.test(pn);
}

//判断是否为CDMA手机号码
function isCDMA(pn)
{
	var reglt = /^1([35]3\d{8}|8[09]\d{8})$/;
	return reglt.test(pn);
}

/*
 * 给定页面对象的内容是否是给定的手机类型
*/
function chkMobile(o,vendor){
	if(!o)	return	"无效的输入！";
	var s = o.value;
	
	s=s.trim();
	if(s.length==0)	{o.focus();	o.select(); return "请输入手机号码";};
	if(!chkFormat(s, "num"))	{o.focus();	o.select(); return "输入中含有无效字符，请重新输入";}
	s=s.lzero();
	if(s.length!=11)	{o.focus();	o.select(); return "输入的号码位数不对，请重新输入";}

	var unicom = isUnicom(s);
	var gmcc   = isGmcc(s);
	var vs	   = isPhone(s);
	var cdma   = isCDMA(s); 
	if(!unicom && !gmcc && !vs &&!cdma)	{o.focus();	o.select(); return "不可识别的手机号码，请重新输入"};

	if(!vendor){
		if(unicom || gmcc || vs)	return "";
	}else if(vendor == "gmcc"){
		if(unicom || cdma)	{o.focus();	o.select(); return "您输入的不是移动号码，请重新输入";}
		else return "";
	}else if(vendor == "unicom"){
		if(gmcc)	{o.focus();	o.select(); return "您输入的不是联通号码，请重新输入";}
		else return "";
	}else{
		if(unicom || gmcc || vs || cdma)	return "";
	}
}
// 判断是否函数
function isFunction(fun){	return typeof fun =="function";	}
// 显示层
function showLayer(ob)	{	ob.style.display = "";	}
// 隐藏层
function hideLayer(ob)	{	ob.style.display = "none";	}

function htmlcode(str,isdecode)
{
		var ar = ['&','&amp;','<','&lt;','>','&gt;',' ','&nbsp;','"','&quot;',"'",'&#39;','\\r','<br>','\\n','<br>'];
		if(isdecode) ar.reverse();
		for(var i=0,r=str;i<ar.length;i+=2) r = r.replace(new RegExp(ar[i],'g'),ar[1+i]);
		return r;
}

function getDataFromQuery(result,name,data)
{
	try
	{		
		var arr = result.split("&");
		for(var i=0;i<arr.length;i++)
		{
			var rname = arr[i].split("=")[0],rvalue = arr[i].split("=")[1];
			if (rname == name)
			{
				var arr2 = rvalue.split(",");
				for(var k=0;k<arr2.length;k++)
					data[arr2[k].split("|")[0]] = arr2[k].split("|")[1];
				break;	
			}
		}
	}catch(e){ }
}

/********************************* javascript AJAX 框架 ************************************************/
// 创建对象
function createXMLHttpRequest(){
	var  xmlhttp;
	try{
		xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
	}catch(e){
		try{
			xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
		}catch(e){
			try{
				xmlhttp = new XMLHttpRequest();
			}catch(e)  {}
		}
	}
	return xmlhttp;
}
//实现函数
function Ajax(){
	var xmlhttp = createXMLHttpRequest();
	var szReturnFlag = 0;
	var reqHeader = "application/x-www-form-urlencoded";

	Ajax.prototype.handleAbort = function (){
		if (1 ==szReturnFlag)	return;
		setTimeout(xmlhttp.abort,  0);
		szReturnFlag = 0;
	}
	Ajax.prototype.setReqHeader = function(fm){
		if(fm)	reqHeader = fm;		
	}
	Ajax.prototype.request = function(url, method ,async, postString, funHandleResult, funHandleExp,funHandleWait){
		if (method != "post") method = "get"; 
        if (async != true) async = true; 
		szReturnFlag = 0;

		xmlhttp.open(method, url, async); 
		xmlhttp.onreadystatechange = function(){
			if ( 4 == xmlhttp.readyState ){
				szReturnFlag = 1;
				if ( 200 == xmlhttp.status){
					funHandleResult(xmlhttp.responseText);
				}else{
					funHandleExp();
				}
			}else{
				try{
					funHandleWait();
				}catch (e){	}
			}
		}
        if (method=="post") {
			xmlhttp.setRequestHeader("Content-type", reqHeader);
			xmlhttp.send(postString);
		} else{
			xmlhttp.send(null); 
		} 
	}
}
/********************************* javascript AJAX 框架 ************************************************/

/********************************* javascript JSLoader 框架 ********************************************/
function JsLoader(){
    this.load = function(url, charset){
        var ss = document.getElementsByTagName("script");
        for(var i = 0;i < ss.length; i++){
            if(ss[i].src && ss[i].src.indexOf(url) != -1) {
                this.onsuccess();
                return;
            }
        }
        var s = document.createElement("script");
        s.type= "text/javascript";
        s.src = url;
        s.charset = charset ? charset : "utf-8";
        var head = document.getElementsByTagName("head")[0];
        head.appendChild(s);
        
        var self = this;
        s.onload = s.onreadystatechange = function() {
            if(this.readyState && this.readyState == "loading")	return;
            self.onsuccess();
        }
        s.onerror = function() {
            head.removeChild(s);
            self.onfailure();
        }
    };
    this.onsuccess=function(){};
    this.onfailure=function(){};
}
/********************************* javascript JSLoader 框架 ********************************************/

/********************************* javascript事件模型框架-eventutil.js *********************************/
// 检测浏览器对象
var sUserAgent = navigator.userAgent.toLowerCase();
var isOpera = sUserAgent.indexOf("opera")>-1;
var isIE = sUserAgent.indexOf("compatible")>-1 && sUserAgent.indexOf("msie")>-1 && !isOpera;
var isWin= (navigator.platform == "Win32" || navigator.platform == "Windows");

var EventUtil = new Object;
//格式化事件，因为IE和其他浏览器下获取事件的方式不同并且事件的属性也不尽相同，通过此方法提供一个一致的事件
EventUtil.formatEvent = function (oEvent) {
     //isIE和isWin引用到一个js文件，判断浏览器和操作系统类型
     if (isIE && isWin) {
         oEvent.charCode = (oEvent.type == "keypress") ? oEvent.keyCode : 0;
         //IE只支持冒泡，不支持捕获
         oEvent.eventPhase = 2;
         oEvent.isChar = (oEvent.charCode > 0);
         oEvent.pageX = oEvent.clientX + document.body.scrollLeft;
         oEvent.pageY = oEvent.clientY + document.body.scrollTop;
         //阻止事件的默认行为
         oEvent.preventDefault = function () {
             this.returnValue = false;
         };

          //将toElement,fromElement转化为标准的relatedTarget
         if (oEvent.type == "mouseout") {
             oEvent.relatedTarget = oEvent.toElement;
         } else if (oEvent.type == "mouseover") {
             oEvent.relatedTarget = oEvent.fromElement;
         }
         //取消冒泡     
         oEvent.stopPropagation = function () {
             this.cancelBubble = true;
         };

         oEvent.target = oEvent.srcElement;
         //添加事件发生时间属性，IE没有
         oEvent.time = (new Date).getTime();
     }
     return oEvent;
};

EventUtil.getEvent = function() {
     if (window.event) {
         //格式化IE的事件
         return this.formatEvent(window.event);
     } else {
         return EventUtil.getEvent.caller.arguments[0];
     }
};
/********************************* javascript事件模型框架-eventutil.js *********************************/

// 判断字符集
function validChars(o, e){
	var e = EventUtil.formatEvent(e);
	if(e.charCode==0)	return true;
	var c = String.fromCharCode(e.charCode);
	var bIs = bIsNot = true;

	s = o.getAttribute("validchars");
	if(s && s.length>0)		bIs = s.indexOf(c) > -1;
	s = o.getAttribute("invalidchars");
	if(s && s.length>0)		bIsNot = s.indexOf(c) == -1;

	return e.ctrlKey || (bIs && bIsNot);
}


//document.domain = "stone.com";
Base = {};
Base.ShopingCart = {
    items : [],
    addItem : function (goodsId, amount)
    {
        if ( !goodsId || !amount || amount <= 0 ) return;
        var xmlHttp = new Ajax();
        var url     = "http://localhost/jiajia/nanbeihuo/index.php?controller=cart&action=additem";
        var postStr = "onshelf_goods_id="+goodsId+"&amount="+amount;
        xmlhttp.request(url, "post", false, postStr, Base.ShopingCart.addItemCallback, emptyFunc,emptyFunc);
    },
    addItemCallback : function(response)
    {
    },
    deleteItem : function(goodsId)
    {
        if ( !goodsId ) return;
        var xmlHttp = new Ajax();
        var url     = "http://localhost/jiajia/nanbeihuo/index.php?controller=cart&action=deleteitem";
        var postStr = "onshelf_goods_id="+goodsId;
        xmlhttp.request(url, "post", false, postStr, Base.ShopingCart.deleteItemCallback, emptyFunc, emptyFunc);
    },
    deleteItemCallback : function(response)
    {
    },
    changeAmount : function (goodsId, amount)
    {
        if ( !goodsId || !amount || amount <= 0 ) return;
        var xmlHttp = new Ajax();
        var url     = "http://localhost/jiajia/nanbeihuo/index.php?controller=cart&action=changeamount";
        var postStr = "onshelf_goods_id="+goodsId+"&amount="+amount;
        xmlhttp.request(url, "post", false, postStr, Base.ShopingCart.changeAmountCallback, emptyFunc,emptyFunc);
    },
    changeAmountCallback : function(response)
    {
    }
};
Base.Order = {
    setOrder : function ()
    {
        var xmlHttp = new Ajax();
        var url     = "http://localhost/jiajia/nanbeihuo/index.php?controller=order&action=setorder";
        xmlhttp.request(url, "post", false, "", Base.Order.setOrderCallback, emptyFunc, emptyFunc);
    },
    setOrderCallback : function(response)
    {
    },
    showOrder : function ()
    {
        var xmlHttp = new Ajax();
        var url     = "http://localhost/jiajia/nanbeihuo/index.php?controller=order&action=showorder";
        xmlhttp.request(url, "post", false, "", Base.Order.showOrderCallback, emptyFunc, emptyFunc);
    },
    showOrderCallback : function(response)
    {
    },
    confirmOrder : function (addressId, paytoolId)
    {
        var xmlHttp = new Ajax();
        var url     = "http://localhost/jiajia/nanbeihuo/index.php?controller=order&action=confirmorder";
        var postStr = "address_id="+goodsId+"&paytool_id="+paytoolId;
        xmlhttp.request(url, "post", false, postStr, Base.Order.confirmOrderCallback, emptyFunc, emptyFunc);
    },
    confirmCallback : function(response)
    {
    },
    checkOrder : function ()
    {
        var xmlHttp = new Ajax();
        var url     = "http://localhost/jiajia/nanbeihuo/index.php?controller=order&action=checkorder";
        xmlhttp.request(url, "post", false, "", Base.Order.checkOrderCallback, emptyFunc, emptyFunc);
    },
    checkOrderCallback : function(response)
    {
    },
    checkOrderProperties : function (orderId)
    {
        var xmlHttp = new Ajax();
        var url     = "http://localhost/jiajia/nanbeihuo/index.php?controller=order&action=checkorderproperties";
        var postStr = "orderId="+orderId;
        xmlhttp.request(url, "post", false, postStr, Base.Order.checkOrderPropertiesCallback, emptyFunc, emptyFunc);
    },
    checkOrderPropertiesCallback : function(response)
    {
    }
}
function emptyFunc()
{
}

